package com.example.samplemanagement.controller;
import com.example.samplemanagement.repository.SampleTrackingRepository;
import com.example.samplemanagement.dto.SampleTrackingHistoryDto;
import com.example.samplemanagement.dto.SampleTrackingOverviewDto;
import com.example.samplemanagement.dto.SampleTrackingRequestDto;
import com.example.samplemanagement.model.SampleTracking;
import com.example.samplemanagement.service.SampleTrackingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.NoSuchElementException;

@RestController
@RequestMapping("/api")
public class SampleTrackingController {

    @Autowired
    private SampleTrackingService sampleTrackingService;

    /**
     * POST /api/sample-tracking
     * 添加新的样品跟踪记录
     * 现在接收 SampleTrackingRequestDto，只包含ID
     */
    @PostMapping("/sample-tracking")
    public ResponseEntity<SampleTracking> addTrackingRecord(@RequestBody SampleTrackingRequestDto requestDto) {
        try {
            SampleTracking savedTracking = sampleTrackingService.addSampleTracking(requestDto);
            return ResponseEntity.status(HttpStatus.CREATED).body(savedTracking);
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("An unexpected error occurred: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * GET /api/sample-tracking
     * 获取所有样品跟踪记录。
     * 此接口用于前端获取总跟踪次数以及用于图表数据（如反馈分布、沟通类型分布）。
     */
    @GetMapping("/sample-tracking") // <-- ADD THIS MAPPING
    public List<SampleTracking> getAllSampleTrackingRecords() {
        return sampleTrackingService.getAllSampleTrackingRecords();
    }


    /**
     * GET /api/sample-tracking-overview
     * 获取样品跟踪概览列表 (聚合数据)
     * 支持根据样品编号、客户名称、状态进行筛选
     * 例如: /api/sample-tracking-overview?sampleNumber=S123&companyName=ABC&status=待转化
     */
    @GetMapping("/sample-tracking-overview")
    public List<SampleTrackingOverviewDto> getSampleTrackingOverview(
            @RequestParam(required = false) String sampleNumber,
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false) String status) {
        return sampleTrackingService.getSampleTrackingOverview(sampleNumber, companyName, status);
    }

    /**
     * GET /api/sample-tracking/history
     * 获取特定样品和客户的所有跟踪历史记录
     * 例如: /api/sample-tracking/history?sampleId=1&customerId=1
     */
    @GetMapping("/sample-tracking/history")
    public ResponseEntity<SampleTrackingHistoryDto> getTrackingHistory(
            @RequestParam Long sampleId,
            @RequestParam Long customerId) {
        try {
            SampleTrackingHistoryDto history = sampleTrackingService.getSampleTrackingHistory(sampleId, customerId);
            return ResponseEntity.ok(history);
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }
    // 修改单条跟踪记录
    @PutMapping("/sample-tracking/{trackingId}")
    public ResponseEntity<SampleTracking> updateTrackingRecord(
            @PathVariable Long trackingId,
            @RequestBody SampleTrackingRequestDto requestDto) {
        try {
            SampleTracking updatedTracking = sampleTrackingService.updateTracking(trackingId, requestDto);
            return ResponseEntity.ok(updatedTracking);
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }
    // 删除单条跟踪记录
    @DeleteMapping("/sample-tracking/{trackingId}")
    public ResponseEntity<Void> deleteSingleTrackingRecord(@PathVariable Long trackingId) {
        try {
            sampleTrackingService.deleteTracking(trackingId);
            return ResponseEntity.noContent().build();
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }
    @DeleteMapping("/sample-tracking/{sampleId}/{customerId}")
    public ResponseEntity<?> deleteTrackingRecords(
            @PathVariable Long sampleId,
            @PathVariable Long customerId) {

        try {
            sampleTrackingService.deleteBySampleAndCustomer(sampleId, customerId);
            return ResponseEntity.noContent().build();
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("删除跟踪记录失败: " + e.getMessage());
        }
    }
    /**
     * PUT /api/sample-tracking-overview/{sampleId}/{customerId}/mark-ordered
     * 标记特定样品-客户组合为已下单
     * 这里的路径变量直接使用 sampleId 和 customerId 更明确
     */
    @PutMapping("/sample-tracking-overview/{sampleId}/{customerId}/mark-ordered")
    public ResponseEntity<Void> markSampleAsOrdered(@PathVariable Long sampleId, @PathVariable Long customerId) {
        try {
            sampleTrackingService.markAsOrdered(sampleId, customerId);
            return ResponseEntity.noContent().build();
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
